package com.xiaoxiong.text;

import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.content.Context;
import android.util.Log;

import com.xiaoxiong.bean.AttendanceData;
import com.xiaoxiong.database.OperateFormAttendanceInfo;

public class DealAttendanceInfoDataByRegular {

	private Context context;
	private String html;
	private Document content;
	private List<AttendanceData> attendanceDatas = new ArrayList<AttendanceData>();

	public DealAttendanceInfoDataByRegular(Context context, String html) {
		super();
		this.context = context;
		this.html = html;
		
		startDeal();
	}

	private void startDeal() {
		
		StringBuilder sb = new StringBuilder(html);
		sb.delete(sb.indexOf("<form"), sb.indexOf("<table width=\"99%\" class=\"table\""))
		.delete(sb.indexOf("<BR>"), sb.indexOf("</body>"));
		this.content = Jsoup.parse(sb.toString());

		Elements element = content
				.getElementsByAttributeValue("align", "center");
		
		String result[] = new String[element.size()];
		int pos = 0;
		for (Element links : element) {
			String title = links.text();
			result[pos++] = title;
		}
		
		for (int i = 3; i < result.length; i += 3) {
//			Log.d("result", result[i] + "\n" + result[i+1] + "\n" + result[i+2]);
			AttendanceData attendanceData = new AttendanceData(
					result[i].replaceAll(" ", ""),
					result[i + 1].replaceAll(" ", ""),
					result[i + 2].replaceAll(" ", ""));
			attendanceDatas.add(attendanceData);
		}
		saveData();
	}

	private void saveData() {

		OperateFormAttendanceInfo ofpi = new OperateFormAttendanceInfo(context);
		ofpi.deleteAllAttendanceInfo();
		int size = attendanceDatas.size();
		for (int i = 0; i < size; ++i) {
			ofpi.insertAttendanceInfo(attendanceDatas.get(i).getcode(),
					attendanceDatas.get(i).getname(), attendanceDatas.get(i)
							.getInfo());
		}
	}
}
